package com.common.redis.util;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonLockUtil {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 获取锁
     * @param lockKey 锁的键
     * @param timeout 等待锁的最大时间
     * @param leaseTime 锁自动释放的时间
     * @return 是否成功获取锁
     */
    public boolean tryLock(String lockKey, long timeout, long leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(timeout, leaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 释放锁
     * @param lockKey 锁的键
     */
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

}
